<template>
  <el-dialog :append-to-body="true" :close-on-click-modal="false" :visible.sync="dialog" style="top:5px;" title="用户选择列表" width="80%">
    <el-row :gutter="6">
      <el-col :span="6">
        <el-input
          v-model="filterOrgSet"
          clearable
          placeholder="输入关键字进行过滤" />
        <el-tree
          ref="orgSetTree"
          :data="orgSetTreeData"
          :props="{children: 'children', label: 'orgName', hasChildren: 'hasChildren'}"
          :filter-node-method="filterOrgSetNode"
          :highlight-current="true"
          node-key="id"
          default-expand-all
          @node-click="handleOrgSetTreeClick"
        >
          <span slot-scope="{ node, data }">
            <svg-icon icon-class="user"/>
            {{ data.orgName }}
          </span>
        </el-tree>
      </el-col>
      <el-col :span="18">
        <!--表格渲染-->
        <DataGridTable
          v-loading="loading"
          :sup_this="sup_this"
          :data="data.rtnList"
          :multi-select="false"
          :show-row-number="true"
          :show-page="false"
          :all-define-columns="['phone','email','userStatus','createDate']"
          grid-id="userMultiSelectListGridId"
          style="width: 100%"
          max-height="400"
          table-ref="userTable"
          @current-change="handleCurrentChange">
          <el-table-column v-if="mult_select" prop="id" width="90px">
            <template slot="header" slot-scope="scope">
              <el-checkbox v-model="checkAll" @change="handleCheckAllChange" />
            </template>
            <template slot-scope="scope">
              <el-button v-if="selectedRows[scope.row.id]" type="danger" size="mini" @click="userCheckSelectChange(scope.row)">取消</el-button>
              <el-button v-else type="primary" size="mini" @click="userCheckSelectChange(scope.row)">选择</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="userAccount" label="用户账号" width="200px">
            <template slot="header" slot-scope="scope">
              <el-input v-model="userAccount" clearable placeholder="输入账号回车过滤" style="width: 100%;" class="filter-item" @keyup.enter.native="userFilterQuery"/>
            </template>
          </el-table-column>
          <el-table-column prop="userName" label="名称" width="200px">
            <template slot="header" slot-scope="scope">
              <el-input v-model="userName" clearable placeholder="输入名称回车过滤" style="width: 100%;" class="filter-item" @keyup.enter.native="userFilterQuery"/>
            </template>
          </el-table-column>
          <el-table-column slot="phone" prop="phone" label="电话" width="200px" />
          <el-table-column slot="email" prop="email" label="邮件" width="200px" />
          <el-table-column slot="userStatus" prop="userStatus" label="用户状态" align="center">
            <template slot-scope="scope">
              <div v-for="item in dicts.user_status" :key="item.id">
                <el-tag v-if="scope.row.userStatus.toString() === item.dictCode" :type="scope.row.userStatus === 'UNLOCK' ? '' : 'info'">{{ item.dictName }}</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column slot="createDate" prop="createDate" label="创建日期" width="200px">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createDate) }}</span>
            </template>
          </el-table-column>
        </DataGridTable>
      </el-col>
    </el-row>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button :loading="loading" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import checkPermission from '@/utils/permission'
import initData from '@/mixins/initData'
import { findUserByOrgCodeUrl } from '@/api/user'
import { getOrgSetsByCpyCode } from '@/api/system/orgSet'
import { parseTime } from '@/utils/index'
import { getUserInfo } from '@/utils/auth'

export default {
  mixins: [initData],
  dictTypes: ['user_status'],
  props: {
    mult_select: {
      default: true,
      requried: false,
      type: Boolean
    }
  },
  data() {
    return {
      loading: false,
      dialog: false,
      selectedRows: [],
      selectedRow: {},
      sup_this: this,
      orgSetTreeData: [],
      filterOrgSet: '',
      userAccount: '',
      userName: '',
      allUserList: [],
      checkAll: false
    }
  },
  watch: {
    filterOrgSet(val) {
      const _thisForm = this.$refs.orgSetTree
      if (_thisForm) {
        this.$refs.orgSetTree.filter(val)
      }
    }
  },
  created() {
    getOrgSetsByCpyCode().then(res => {
      this.orgSetTreeData = res.data
      const allObject = { id: 'all', orgCode: '', orgName: '+所有用户' }
      this.orgSetTreeData.unshift(allObject)
    })
    this.url = findUserByOrgCodeUrl()
    this.pageCount = false
  },
  mounted() {
  },
  methods: {
    parseTime,
    checkPermission,
    loadData() {
      this.paramBean.orgCode = ''
      this.init()
    },
    async beforeInit() {
      this.checkAll = false
      this.selectedRows = []
      this.selectedRow = {}
      this.paramBean.cpyCode = getUserInfo().cpyCode
      return true
    },
    afterInit(res) {
      this.allUserList = res.data.rtnList
    },
    userFilterQuery() {
      const userAccount = this.userAccount
      const userName = this.userName
      if (userAccount || userName) {
        this.data.rtnList = this.allUserList.filter(user => {
          return user.userAccount.includes(userAccount) && user.userName.includes(userName)
        })
      } else {
        this.data.rtnList = this.allUserList
      }
    },
    handleSelectionChange(val) {
      this.selectedRows = val
    },
    doSubmit() {
      this.loading = true
      if (this.mult_select) {
        const _selectRows = this.selectedRows
        const tmpKeys = Object.keys(_selectRows)
        const tmpRows = []
        for (const tmpKey of tmpKeys) {
          tmpRows.push(_selectRows[tmpKey])
        }
        this.$emit('userSelectCallback', tmpRows, this)
      } else {
        this.$emit('userSelectCallback', this.selectedRow, this)
      }
    },
    cancel() {
      this.dialog = false
      this.allUserList = []
    },
    handleCurrentChange(val) {
      this.selectedRow = val
    },
    handleCheckAllChange(isChecked) {
      const tmpSelectRows = this.selectedRows
      if (isChecked) {
        this.data.rtnList.forEach(row => {
          tmpSelectRows[row.id] = row
        })
      } else {
        // 取消
        this.data.rtnList.forEach(row => {
          delete tmpSelectRows[row.id]
        })
      }
      this.selectedRows.splice(this.selectedRows.length)
      // this.trees[idx] = 'x' // 无响应
      // this.$set(this.trees,idx,'x') // 有响应
      // this.trees.splice(idx,1,'x') // 有响应
    },
    userCheckSelectChange(userRow) {
      if (!this.selectedRows[userRow.id]) {
        // 选择
        this.selectedRows[userRow.id] = userRow
      } else {
        delete this.selectedRows[userRow.id]
      }
      this.selectedRows.splice(this.selectedRows.length)
    },
    handleOrgSetTreeClick(data) {
      this.paramBean.orgCode = data.orgCode
      this.init()
    },
    filterOrgSetNode(value, data) {
      if (!value) return true
      return data.orgName.indexOf(value) !== -1
    }
  }
}
</script>
